package com.sumu.today.models.permission.commons;

import com.baomidou.kaptcha.exception.KaptchaException;
import com.baomidou.kaptcha.exception.KaptchaIncorrectException;
import com.baomidou.kaptcha.exception.KaptchaNotFoundException;
import com.baomidou.kaptcha.exception.KaptchaTimeoutException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = KaptchaException.class)
    public ModelAndView kaptchaExceptionHandler(KaptchaException kaptchaException, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(request.getRequestURI());
        if (kaptchaException instanceof KaptchaIncorrectException) {
            modelAndView.addObject("error", "验证码不正确");
            return modelAndView;
        } else if (kaptchaException instanceof KaptchaNotFoundException) {
            modelAndView.addObject("error", "验证码未找到");
            return modelAndView;
        } else if (kaptchaException instanceof KaptchaTimeoutException) {
            modelAndView.addObject("error", "验证码过期");
            return modelAndView;
        } else {
            modelAndView.addObject("error", "验证码渲染失败");
            return modelAndView;
        }
    }

}